package com.yunjian.core.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunjian.common.annotation.SysLog;
import com.yunjian.common.utils.*;
import com.yunjian.common.validator.Assert;
import com.yunjian.common.validator.ValidatorUtils;
import com.yunjian.common.validator.group.AddGroup;
import com.yunjian.common.validator.group.UpdateGroup;
import com.yunjian.core.dto.SysUserDto;
import com.yunjian.core.entity.*;
import com.yunjian.core.form.PasswordForm;
import com.yunjian.core.service.*;
import net.sf.json.JSONArray;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 系统用户
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;

    @Value("${template.distributor.url}")
    private String userTemplate = "";


    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        //只有超级管理员，才能进入到这个接口里面来
		/*SysUserRoleEntity entity = sysUserRoleService.getOne(new QueryWrapper<SysUserRoleEntity>()
				.eq("user_id", getUserId()));
		SysRoleEntity role = sysRoleService.getOne(new QueryWrapper<SysRoleEntity>()
				.eq("role_id", entity.getRoleId()));
		if(entity != null && role != null && role.getType() != 1){
			params.put("createUserId", getUserId());
		}*/
        PageUtils page = sysUserService.queryPage(params);
        return R.ok().put("page", page);
    }

    @GetMapping("/dealerList")
    public R dealerList(@RequestParam Map<String, Object> params) {
        List<SysUserRoleEntity> list = sysUserRoleService.list(new QueryWrapper<SysUserRoleEntity>()
                .gt("role_id", 1));
        List<Long> userIdList = new ArrayList<>();
        list.forEach(item -> {
            userIdList.add(item.getUserId());
        });

        String username = (String) params.get("username");

        IPage<SysUserEntity> page = sysUserService.page(
                new Query<SysUserEntity>().getPage(params),
                new QueryWrapper<SysUserEntity>().eq("delete_flag", 1)
                        .like(StringUtils.isNotBlank(username), "username", username)
                        .in("user_id", userIdList).orderByDesc("create_time")
        );
        PageUtils pageUtils = new PageUtils(page);

        int isAdmin = 0;
        SysUserEntity loginUser = HttpContextUtils.getLoginSysUserEntity();
        SysUserRoleEntity userRoleEntity = sysUserRoleService.getOne(new QueryWrapper<SysUserRoleEntity>()
                .eq("user_id", loginUser.getUserId()));
        if (userRoleEntity.getRoleId().intValue() == Constant.SUPER_ADMIN
                || userRoleEntity.getRoleId().intValue() == Constant.SUPER_DEALER) {
            isAdmin = 1;
        }

        return R.ok().put("page", pageUtils).put("isAdmin", isAdmin);
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form) {
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        List<SysRoleEntity> roleList = sysRoleService.list(new QueryWrapper<SysRoleEntity>().gt("role_id", 1));

        List<Country> countries = countryService.list();
        List<Region> provinceList = regionService.list(new QueryWrapper<Region>().eq("level_type", 2));
        List<Region> cityList = regionService.list(new QueryWrapper<Region>().eq("level_type", 3).eq("parent_id", user.getProvinceId()));
        List<Region> distinctList = regionService.list(new QueryWrapper<Region>().eq("level_type", 4).eq("parent_id", user.getCityId()));

        return R.ok().put("user", user).put("roleList", roleList)
                .put("countries", countries).put("provinceList", provinceList)
                .put("cityList", cityList).put("districtList", distinctList);
    }

    @Autowired
    private ICountryService countryService;
    @Autowired
    private IRegionService regionService;

    /**
     * 用户信息
     */
    @GetMapping("/regionInfo")
    public R regionInfo() {
        List<Country> countries = countryService.list();
        List<Region> provinceList = regionService.list(new QueryWrapper<Region>().eq("level_type", 2));
        List<SysRoleEntity> roleList = sysRoleService.list(new QueryWrapper<SysRoleEntity>().gt("role_id", 1));
        return R.ok().put("countries", countries).put("provinceList", provinceList).put("roleList", roleList);
    }

    @PostMapping("/queryCityListByProvince")
    public R queryCityListByProvince(@RequestBody Map<String, Object> param) {
        String provinceId = StringUtil.obj2String(param.get("provinceId"));
        List<Region> cityList = regionService.list(new QueryWrapper<Region>()
                .eq("level_type", 3)
                .eq("parent_id", Integer.parseInt(provinceId)));
        return R.ok().put("cityList", cityList);
    }

    @PostMapping("/queryDistrictListByCity")
    public R queryDistrictListByCity(@RequestBody Map<String, Object> param) {
        String cityId = StringUtil.obj2String(param.get("cityId"));
        List<Region> districtList = regionService.list(new QueryWrapper<Region>()
                .eq("level_type", 4)
                .eq("parent_id", Integer.parseInt(cityId)));
        return R.ok().put("districtList", districtList);
    }

    /**
     * 用户信息
     */
    @PostMapping("/getUserInfo")
    public R getUserInfo() {
        SysUserEntity cacheUser = HttpContextUtils.getLoginSysUserEntity();
        logger.info("查询用户信息{}", cacheUser);
        SysUserEntity user = sysUserService.getOne(new QueryWrapper<SysUserEntity>()
                .eq("user_id", cacheUser.getUserId()));

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(cacheUser.getUserId());
        user.setRoleIdList(roleIdList);

        List<SysRoleEntity> roleList = sysRoleService.list(new QueryWrapper<SysRoleEntity>().gt("role_id", 1));
        return R.ok().put("user", user).put("roleList", roleList);
    }

    @GetMapping("/dealerInfo/{userId}")
    public R dealerInfo(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);
        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        SysRoleEntity role = sysRoleService.getOne(new QueryWrapper<SysRoleEntity>().eq("role_id", roleIdList.get(0)));
        user.setRoleIdList(roleIdList);
        return R.ok().put("user", user).put("role", role);
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @PostMapping("/save")
    public R save(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);

        user.setCreateUserId(getUserId());
        if (user.getCountryId() != null) {
            Country country = countryService.getOne(new QueryWrapper<Country>().eq("id", user.getCountryId()));
            user.setCountryName(country != null ? country.getTitle() : "");
        }
        if (user.getProvinceId() != null) {
            Region province = regionService.getOne(new QueryWrapper<Region>().eq("id", user.getProvinceId()));
            user.setProvinceName(province != null ? province.getName() : "");
        }
        if (user.getCityId() != null) {
            Region city = regionService.getOne(new QueryWrapper<Region>().eq("id", user.getCityId()));
            user.setCityName(city.getName());
        }
        if (user.getDistrictId() != null) {
            Region district = regionService.getOne(new QueryWrapper<Region>().eq("id", user.getCityId()));
            user.setDistrictName(district != null ? district.getName() : "");
        }
        sysUserService.saveUser(user);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/update")
    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);
        if (user.getRoleIdList().size() > 1) {
            return R.error("用户只能指定一个角色");
        }

        user.setCreateUserId(getUserId());
        sysUserService.update(user);

        if (user.getCountryId() != null) {
            Country country = countryService.getOne(new QueryWrapper<Country>().eq("id", user.getCountryId()));
            user.setCountryName(country != null ? country.getTitle() : "");
        }
        if (user.getProvinceId() != null) {
            Region province = regionService.getOne(new QueryWrapper<Region>().eq("id", user.getProvinceId()));
            user.setProvinceName(province != null ? province.getName() : "");
        }
        if (user.getCityId() != null) {
            Region city = regionService.getOne(new QueryWrapper<Region>().eq("id", user.getCityId()));
            user.setCityName(city.getName());
        }
        if (user.getDistrictId() != null) {
            Region district = regionService.getOne(new QueryWrapper<Region>().eq("id", user.getCityId()));
            user.setDistrictName(district != null ? district.getName() : "");
        }

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/updateDealer")
    public R updateDealer(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);
        user.setCreateUserId(getUserId());
        sysUserService.update(user);
        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] userIds) {
        logger.info("删除用户", userIds[0]);
        SysUserEntity user = sysUserService.getOne(new QueryWrapper<SysUserEntity>()
                .eq("user_id", userIds[0]));
        SysUserRoleEntity userRoleEntity = sysUserRoleService.getOne(new QueryWrapper<SysUserRoleEntity>()
                .eq("user_id", userIds[0]));
        if (userRoleEntity.getRoleId().intValue() == Constant.SUPER_ADMIN
                || userRoleEntity.getRoleId().intValue() == Constant.SUPER_DEALER) {
            logger.error("系统管理员不能删除");
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            logger.error("当前用户不能删除自己");
            return R.error("当前用户不能删除自己");
        }

        //逻辑删除
        user.setDeleteFlag(0);
        sysUserService.saveOrUpdate(user);
        //sysUserService.deleteBatch(userIds);

        return R.ok();
    }

    /**
     * 下载经销商信息模板
     */
    @PostMapping("/downUserInfoTemplate")
    public R downTemplate() {
        logger.info("经销商模板文件地址：{}", userTemplate);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        return R.ok().put("userTemplate", userTemplate).put("token", token);
    }

    /**
     * 切换语言
     */
    @PostMapping("/changeLocal")
    public R changeLocal(@RequestBody Map<String, Object> params) {
        String language = (String) params.get("language");
        SysUserEntity user = (SysUserEntity) HttpContextUtils.getLoginUser().get("sysUser");
        user.setLanguage(language);
        sysUserService.changeLocal(user);
        return R.ok();
    }

    @PostMapping("/getLoginUserInfo")
    public R getLoginUserInfo(@RequestBody Map<String, Object> params) {
        SysUserEntity user = (SysUserEntity) HttpContextUtils.getLoginSysUserEntity();

        List<SysUserRoleEntity> list = sysUserRoleService.list(new QueryWrapper<SysUserRoleEntity>().eq("role_id", Constant.SUPER_DEALER));
        if (!list.isEmpty()) {
            SysUserEntity userEntity = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_id", list.get(0).getUserId()));
            SysUserDto u = new SysUserDto();
            BeanUtils.copyProperties(userEntity, u);
            return R.ok().put("user", u);
        } else {
            return R.ok();
        }
    }

    /**
     * 导入并保存经销商信息
     */
    @SuppressWarnings("unchecked")
    @PostMapping("/uploadUserInfoFile")
    public R importUserInfo(@RequestParam("file") MultipartFile file) {
        File uploadFile = FileUtil.multipartFileToFile(file);
        JSONArray array = ExcelUtil.readExcel(uploadFile);
        logger.info("解析数据{}", JsonUtil.toJsonString(array));
        uploadFile.delete();
        List<SysUserEntity> resultList = new ArrayList<>();
        SysUserEntity loginUser = HttpContextUtils.getLoginSysUserEntity();
        try {
            if (array.size() > 0) {
                for (Object item : array) {
                    logger.info("解析对象{}", item.toString());
                    Map<String, Object> map = JsonUtil.toMap(item.toString());

                    SysUserEntity sysUser = new SysUserEntity();
                    sysUser.setUsername(map.get("0").toString().trim());
                    String salt = RandomStringUtils.randomAlphanumeric(20);
                    sysUser.setSalt(salt);
                    sysUser.setPassword(new Sha256Hash(map.get("1").toString().trim(), salt).toHex());
                    sysUser.setCompany(map.get("2").toString().trim());
                    sysUser.setContact(map.get("3").toString().trim());
                    sysUser.setMobile(map.get("4").toString().trim());
                    sysUser.setEmail(map.get("5").toString().trim());
                    sysUser.setStatus(1);
                    sysUser.setCreateTime(new Date());
                    sysUser.setCreateUserId(loginUser.getUserId());
                    resultList.add(sysUser);
                }
                return sysUserService.saveBatchRecord(resultList);
            } else {
                return R.error("经销商内容为空");
            }
        } catch (Exception e) {
            logger.error("导入经销商信息失败", e);
            return R.error("导入经销商信息失败");
        }
    }
}
